package com.eims.sls_app.ui;

import android.R.anim;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.RequestParams;
import bls.juejin.cn.R;
import com.eims.sls_app.dataaccess.MyDrawData;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.RequestUtil;
import com.eims.sls_app.view.MyBankSpinner;
import com.eims.sls_app.view.MyToast;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 提款
 * 
 */
public class WithdrawalActivity extends MyBaseActivity implements OnClickListener {
	private Context context = WithdrawalActivity.this;
	private static final String TAG = "WithdrawalActivity";
	private TextView tv_bankName, tv_location, tv_zhiName;
	private TextView tv_cardNum, tv_name, tv_tip_info;
	private EditText et_money;
	public EditText et_question;
	private EditText et_answer;
	private Button btn_ok;
	private ImageButton btn_back, btn_question;
	private String opt, auth, info, time, imei, crc; // 格式化后的参数

	private MyBankSpinner spinner_question;
	private MyBankSpinner spinner_moneyType;
	public int question_index = 0;
	public int money_index = 0;
	private MyAsynTask myAsynTask;
	private String qId, qAnswer, money;
	private List<Map<String, String>> listQuestion = new ArrayList<Map<String, String>>();

	private List<Map<String, String>> moneyType = new ArrayList<Map<String, String>>();

	private List<String> mData = new ArrayList<String>();
	private MyHander mHander = new MyHander();
	private Dialog dialog;

	// 新增参数
	private String DrawType;// 提款类型

	// 新增控件
	private TextView tvBalance;
	private TextView tvAllowCaiJin;
	public EditText edMoneyType;
	private ImageButton btnMoneyType;
	private TextView tvLastMoney;// 动态变动
	private TextView tvBankPlace; // 开发地
	private TextView tvBank; // 开发行

	private MyDrawData myDrawData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_withdrawal);
		findView();
		getInitDraw();
		getSiteNameAndPhone();
		inData();
	}

	private void inData() {
		mData.add("金额");
		mData.add("彩金");
		for (int i = 0; i < mData.size(); i++) {
			HashMap<String, String> maps = new HashMap<String, String>();
			maps.put("name", mData.get(i));
			moneyType.add(maps);
		}
	}

	/** 初始化提款申请参数 */
	private void init() {
		info = RspBodyBaseBean.changeWithdrawal_info(et_money.getText().toString().trim(), qId, qAnswer, DrawType);
		// String key = MD5.md5(App.user.getUserPass() + App.MD5_key);
		String key = App.key;
		crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
		auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
	}

	/** 初始化UI */
	private void findView() {
		opt = "37";
		time = RspBodyBaseBean.getTime();
		imei = RspBodyBaseBean.getIMEI(this);
		btn_back = (ImageButton) findViewById(R.id.btn_back);
		// tv_bankName = (TextView)
		// this.findViewById(R.id.withdrawal_tv_bankName2);
		tv_location = (TextView) this.findViewById(R.id.withdrawal_tv_location2);
		tv_zhiName = (TextView) this.findViewById(R.id.withdrawal_tv_fullName2);
		tv_cardNum = (TextView) this.findViewById(R.id.withdrawal_tv_bankNum2);
		tv_name = (TextView) this.findViewById(R.id.withdrawal_tv_name2);
		tv_tip_info = (TextView) this.findViewById(R.id.tv_tip_info);

		et_money = (EditText) this.findViewById(R.id.withdrawal_et_money);
		et_question = (EditText) this.findViewById(R.id.withdrawal_et_soft);
		et_answer = (EditText) this.findViewById(R.id.withdrawal_et_answer);
		btn_question = (ImageButton) this.findViewById(R.id.withDrawal_btn_soft);
		btn_ok = (Button) this.findViewById(R.id.withdrawal_btn_ok);
		// 新增控件
		tvBalance = (TextView) findViewById(R.id.withdrawal_tv_amount2);
		tvAllowCaiJin = (TextView) findViewById(R.id.withdrawal_tv_CaiJin2);
		// tvBankPlace=(TextView) findViewById(R.id.withdrawal_tv_bankPlace2);
		// tvBank=(TextView) findViewById(R.id.withdrawal_tv_bank2);
		// tv_bankName.setText(App.user.getBankName());
		// tv_location.setText(App.user.getProvinceName()
		// + App.user.getCityName());
		// tv_zhiName.setText(App.user.getFullName());
		// tv_cardNum.setText(App.user.getBangNum());
		// tv_name.setText(App.user.getRealityName());
		// et_money.setText("20");
		setCursorPosition(et_money);
		tv_tip_info.setText(
				"为了保障您的资金安全，亲的提款申请成功，并经核对无误后，将通过人工核对后再汇到您的账户；" + "\n" + "1.针对用户正常提款申请，上班时间（10:00-22:30）内客服人员会在2小时内处理完成。"
						+ "\n" + "2.您在工作时间内的提款我们2小时内给您处理，超过2小时每1时我们给您5元的滞纳金，50元封顶。");
		if (listQuestion.size() == 0) {
			getData();
		}
	//	et_question.setText(App.user.getSecurityQuestionId());
//		Log.e(TAG, "findView: "+App.user.toString());
		Log.e(TAG, "findView: "+listQuestion.toString());
		if (null != App.user.getSecurityQuestionId()&&!App.user.getSecurityQuestionId().equals("")) {

			question_index = Integer.parseInt(App.user.getSecurityQuestionIndex())-1;
			Log.e(TAG, "findView: "+question_index);
					et_question.setText(App.user.getSecurityQuestionId());


//			for (int i = 0; i < listQuestion.size(); i++) {
//				Map<String, String> map = listQuestion.get(i);
//				String question = map.get("name");
//				Log.e(TAG, "question: "+question );
//				String uq = App.user.getSecurityQuestionId();
//				Log.e(TAG, "uq: "+uq );
//				if (null != question && question.equals(uq)) {
//					String qid = i + "";
//					question_index = Integer.parseInt(qid);
//					et_question.setText(question);
//				}
//			}
		}

		edMoneyType = (EditText) findViewById(R.id.ed_moneyType);

		btnMoneyType = (ImageButton) findViewById(R.id.withdraw_btn_soft2);
		tvLastMoney = (TextView) findViewById(R.id.withdrawal_tv_lastmoney);

	}

	/** 绑定监听 */
	private void setListener() {
		btn_back.setOnClickListener(this);
		btn_ok.setOnClickListener(this);
		btn_question.setVisibility(View.GONE);
		// btn_question.setOnClickListener(this);
		et_money.addTextChangedListener(watcher);
		edMoneyType.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.length() == 0) {

				} else {

					mHander.sendEmptyMessage(12);

				}

			}
		});

		btnMoneyType.setOnClickListener(this);
	}

	/**
	 * 获取站点名称和客服电话
	 */
	public void getSiteNameAndPhone() {
		RequestUtil requestUtil = new RequestUtil(WithdrawalActivity.this, false, 0, false, "正在加载用户信息...") {
			@Override
			public void responseCallback(JSONObject jsonObject) {
				if (RequestUtil.DEBUG)
					Log.e(TAG, "获取站点名称和客服电话jsonObject--- " + jsonObject.toString());
				if (null != jsonObject) {
					String name = jsonObject.optString("SiteName");
					String phone = jsonObject.optString("Phone");
					if (!"".equals(name)) {
						App.APP_NAME = name;
					}
					if (!"".equals(phone)) {
						App.SERVICE_PHONE = phone;
					}
				} else {
					if (RequestUtil.DEBUG)
						Log.e(TAG, "获取站点名称和客服电话---返回结果为空");
				}
				findView();
				setListener();
				dialog = RequestUtil.createLoadingDialog(context, "正在提款...", true);
			}

			@Override
			public void responseError(VolleyError error) {
				if (RequestUtil.DEBUG)
					Log.e(TAG, "获取站点名称和客服电话出错--- " + error.getMessage());
				findView();
				setListener();
				dialog = RequestUtil.createLoadingDialog(context, "正在提款...", true);
			}
		};
		requestUtil.getSiteNameAndPhone();
	}

	private void getInitDraw() {

		RequestUtil requestUtil = new RequestUtil(context, false, 0) {

			@Override
			public void responseError(VolleyError error) {

				RequestParams.convertError(context, error, true);

			}

			@Override
			public void responseCallback(JSONObject reponseJson) {
				Log.e("MyJson41", reponseJson.toString());
				String MyJson = reponseJson.toString();
				Log.i(TAG, "=====MyJson" + MyJson);
				if (null != reponseJson) {
					myDrawData = JSON.parseObject(MyJson, MyDrawData.class);
					int error = myDrawData.getError();
					// Log.e("code", error+"");
					if (error == 0) {

						mHander.sendEmptyMessage(11);

					} else {
						Toast.makeText(context, "数据初始化失败", Toast.LENGTH_SHORT).show();
					}
				}

			}
		};
		requestUtil.getInitParams41();

	}

	/** 点击监听 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.withdrawal_btn_ok:
			if (outOfRange())
				return;
			qAnswer = et_answer.getText().toString().trim();
			money = et_money.getText().toString().trim();
			if (question_index != -1) {
				for (Object o : listQuestion.get(question_index).entrySet()) {
					Entry entry = (Entry) o;
					String key = (String) entry.getKey();
					if ("id".equals(key)) {
						qId = (String) entry.getValue();
					}
				}
			} else {
				Toast.makeText(WithdrawalActivity.this, "保密问题不能为空", Toast.LENGTH_SHORT).show();
				return;
			}

			if ("".equals(edMoneyType.getText().toString().trim())) {
				Toast.makeText(context, "提款类型不能为空", Toast.LENGTH_SHORT).show();
				return;
			}
			// if(myDrawData.getHandselDrawing()!=1){
			//
			// MyToast.getToast(WithdrawalActivity.this, "该用户暂不支持提款").show();
			//
			// return;
			// }
			if (qAnswer.length() == 0) {
				MyToast.getToast(WithdrawalActivity.this, "答案不能为空").show();
				return;
			} else if (money.length() == 0) {
				MyToast.getToast(WithdrawalActivity.this, "提款金额不能为空").show();
				return;
			} else if (Integer.parseInt(money) < 50) {
				MyToast.getToast(WithdrawalActivity.this, "提款金额必须大于等于50元。").show();
			} else {
				btn_ok.setEnabled(false);
				myAsynTask = new MyAsynTask();
				myAsynTask.execute();
			}
			break;
		case R.id.withDrawal_btn_soft:
			spinner_question = new MyBankSpinner(WithdrawalActivity.this, listQuestion, question_index,
					App.QUESTION_TYPE2, R.style.dialog);
			spinner_question.show();
			break;
		case R.id.withdraw_btn_soft2:
			spinner_moneyType = new MyBankSpinner(context, moneyType, money_index, App.MONEY_TYPE, R.style.dialog);
			spinner_moneyType.show();
			break;

		case R.id.btn_back:
			finish();
			break;
		}
	}

	/** 文本框 监听 */
	private TextWatcher watcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable s) {
			String text = s.toString();

			/*
			 * if (null != text && !"".equals(text)) { int money_text =
			 * Integer.parseInt(text);; } else { //et_money.setText((int) money_text + "");
			 * MyToast.getToast(WithdrawalActivity.this, "提现金额至少是50元").show(); }
			 */

			double money_max = Double.parseDouble(App.user.getBalance());
			/*
			 * if(money_text<20){ et_money.setText("20"); money = "20";
			 * MyToast.getToast(WithdrawalActivity.this,"至少提款20元").show(); return; }else
			 */
			if (null != text && !"".equals(text)) {
				// int money_text = Integer.parseInt(text);;
				if (50 > Integer.parseInt(text)) {

					// MyToast.getToast(WithdrawalActivity.this, "提现金额至少是50元").show();
				}
				if (Integer.parseInt(text) > money_max) {// 输入金额大于可用余额
					et_money.setText((int) money_max + "");
					money = (int) money_max + "";
					MyToast.getToast(WithdrawalActivity.this, "输入金额不可大于可用余额").show();
					return;
				}
			}
			setCursorPosition(et_money);
			money = s.toString().trim();
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}
	};

	public void setCursorPosition(EditText et) {
		CharSequence text = et.getText();
		if (text != null) {
			Selection.setSelection((Spannable) text, text.length());
		}
	}

	String msgs;

	/** 异步任务 */
	class MyAsynTask extends AsyncTask<Integer, Integer, String> {
		@Override
		protected String doInBackground(Integer... params) {
			init();
			String[] values = { opt, auth, info };
			System.out.println(info);
			String result = HttpUtils.doPost(App.names, values, App.path);
			System.out.println("提款提示：" + result);

			if ("-500".equals(result))
				return result;

			JSONObject object;
			try {
				object = new JSONObject(result);
				if ("0".equals(object.getString("error"))) {
					String userInfo = object.getString("dtUserInfo");
					JSONArray array = new JSONArray(userInfo);
					JSONObject item = array.getJSONObject(0);
					App.user.setBalance(item.getLong("balance"));
					App.user.setFreeze(item.getDouble("freeze"));
					Log.i("x", "提款成功");
				} else {
					msgs = object.getString("msg");
				}
				// 更新消息
				return object.getString("error");
			} catch (Exception e) {
				e.printStackTrace();
				Log.i("x", "提款失败" + e.getMessage());
			}
			return "1";
		}

		/** 最开始执行的 */
		@Override
		protected void onPreExecute() {
			if (null != dialog)
				dialog.show();
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {
			if (null != dialog && dialog.isShowing())
				dialog.dismiss();
			btn_ok.setEnabled(true);
			mHander.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	/** 解析问题的XML */
	private void getData() {
		// 先清除
		listQuestion.clear();
		XmlResourceParser xrp = getResources().getXml(R.xml.question);
		try {
			Map<String, String> map = null;
			// 直到文档的结尾处
			while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
				// 如果遇到了开始标签
				if (xrp.getEventType() == XmlResourceParser.START_TAG) {
					String tagName = xrp.getName();// 获取标签的名字
					if (tagName.equals("row")) {
						map = new HashMap<String, String>();
						String id = xrp.getAttributeValue(null, "id");// 通过属性名来获取属性值
						String nm = xrp.getAttributeValue(null, "question");// 通过属性名来获取属性值

						map.put("id", id);
						map.put("name", nm);

						listQuestion.add(map);
					}
				}
				xrp.next();// 获取解析下一个事件
			}
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressLint("HandlerLeak")
	class MyHander extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				MyToast.getToast(WithdrawalActivity.this, "提款申请成功，请等待处理。").show();
				WithdrawalActivity.this.finish();
				break;
			case -174:
				MyToast.getToast(WithdrawalActivity.this, msgs).show();
				et_answer.setText("");
				break;
			case -178:
				MyToast.getToast(WithdrawalActivity.this, "余额不足").show();
				break;
			case -500:
				MyToast.getToast(WithdrawalActivity.this, "连接超时").show();
				break;
			case -176:
				MyToast.getToast(WithdrawalActivity.this, "请完善支付宝信息，开户名未绑定").show();
				break;

			// 有问题，在处理
			case 12:
				String name = edMoneyType.getText().toString().trim();
				if (name.equals("金额")) {

					tvLastMoney.setText("提款金额:");
					DrawType = "0";

					et_money.setHint("可提款金额" + myDrawData.getBalance() + "元");
				} else if (name.equals("彩金")) {

					tvLastMoney.setText("提款彩金");
					DrawType = "1";
					et_money.setHint("可提款彩金" + myDrawData.getUserAllowHandsel() + "元");
				}

				break;
			case 11:

				tvBalance.setText(myDrawData.getBalance() + "元");
				tvAllowCaiJin.setText(myDrawData.getUserAllowHandsel() + "元");
				tv_name.setText(myDrawData.getRealityName().substring(0, 1) + "**");
				// tv_bankName.setText(myDrawData.getBankTypeName());
				String BankCard = myDrawData.getBankCardNumber();
				if(!BankCard.equals("")){

					tv_cardNum.setText(BankCard.substring(0, 3) + "****" + BankCard.substring(BankCard.length() - 4));
				}


				// tvBankPlace.setText(myDrawData.getProvinceName()+myDrawData.getCityName());
				// tvBank.setText(myDrawData.getBranchBankName());
				et_money.setHint("可提款金额" + myDrawData.getBalance() + "元");
				if (myDrawData.getHandselDrawing() != 1) {

					btnMoneyType.setEnabled(false);
				}

				edMoneyType.setText("金额");
				String name2 = edMoneyType.getText().toString().trim();
				if (name2.equals("金额")) {

					tvLastMoney.setText("提款金额:");
					DrawType = "0";

				} else if (name2.equals("彩金")) {

					tvLastMoney.setText("提款彩金");
					DrawType = "1";
				}

				break;
			default:
				MyToast.getToast(WithdrawalActivity.this, "操作失败").show();
				break;
			}
			super.handleMessage(msg);
		}
	}

	private boolean outOfRange() {
		String money = et_money.getText().toString().trim();

		if (money == null) {
			MyToast.getToast(WithdrawalActivity.this, "请输入提款金额").show();
			setCursorPosition(et_money);
			return true;
		}
		if ("".equals(money)) {
			MyToast.getToast(WithdrawalActivity.this, "请输入提款金额").show();
			setCursorPosition(et_money);
			return true;
		}
		if (null != money && !"".equals(money)) {
			money = money + ".0";
			double money_text = Double.parseDouble(money);
			double money_max = Double.parseDouble(App.user.getBalance());
			// if(money_text<20){
			// et_money.setText("20");
			// MyToast.getToast(WithdrawalActivity.this,"至少提款20元").show();
			// setCursorPosition(et_money);
			// return true;
			// }else
			if (money_text > money_max) {// 输入金额大于可用余额
				et_money.setText((int) money_max + "");
				MyToast.getToast(WithdrawalActivity.this, "可提现金额不足").show();
				setCursorPosition(et_money);
				return true;
			}
		}
		return false;
	}
}
